// 处理 用户登录相关的action
// token => 更新token
import * as types from "../actionType"
import { setToken as setTokenLocal, clearToken } from "@/utils/auth"
import http from "@/utils/http"

export const setToken = (payload) => ({ type: types.SET_TOKEN, payload }) // action Creator

export const updateUser = (payload) => ({
  type: types.UPDATE_USERINFO,
  payload,
})

// data => mobile-code
export const loginAction = (data) => {
  return async (dispatch) => {
    // 发起异步请求
    const {
      data: { token },
    } = await http.post("/v1_0/authorizations", data)
    // 打印token
    // localStorage.setItem("geek-pc-19", token) // 写入到本地缓存
    setTokenLocal(token)
    // 同步到redux
    dispatch(setToken(token))
  }
}

// dispatch => {}
export const getUserInfo = () => {
  return async (dispatch) => {
    // 异步请求
    const { data } = await http.get("/v1_0/user/profile")
    dispatch(updateUser(data)) // dispatch => 对象 payload => 用户信息
  }
}

export const logoutAction = () => {
  return (dispatch) => {
    // 删除本地缓存
    clearToken() // 清空本地缓存
    dispatch(setToken("")) // 清空redux中的token
    dispatch(updateUser({})) // 清空用户信息
  }
}
